import { config } from '../config.js'

const tips = {
  1: '报错，出现了一个错误',
  1005: '不正确的开发者key',
  200: '你已经点过赞了',
  2001: '你还没点过赞',
  3000: '不正确的开发者key'
}

class HTTP {
  request (params) {
    let { url, method = 'GET', data, success } = params
    const { api_base_url, appkey } = config

    wx.request({
      url: api_base_url + url,
      method,
      data,
      header: {
        'content-type': 'application/json',
        appkey
      },
      success: (res) => {
        const { statusCode, data } = res
        const { error_code } = data
        if (statusCode.toString().startsWith('2')) {
          success && success(data)
        } else {
          this._showError(error_code)
        }
      },
      fail: (err) => {
        this._showError(1)
      }
    })
  }

  _showError (errorCode) {
    if (!errorCode) {
      errorCode = 1
    }
    wx.showToast({
      title: tips[errorCode] || tips[1],
      icon: 'none',
      duration: 3000
    })
  }
}

export { HTTP }
